<template>
  <div>
    <el-card>
      <Bread first="个人中心" second="重置密码"></Bread>
      <el-form
        :model="resetForm"
        :rules="rulesForm"
        ref="resetPwdRef"
        label-width="80px"
      >
        <el-form-item prop="old_pwd" label="原密码">
          <el-input
            v-model="resetForm.old_pwd"
            placeholder="请输入原密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="new_pwd" label="新密码">
          <el-input
            v-model="resetForm.new_pwd"
            placeholder="请输入新密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="re_pwd" label="确认新密码">
          <el-input
            v-model="resetForm.re_pwd"
            placeholder="请再次输入新密码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="modifyPwdFn">修改密码</el-button>
          <el-button @click="resetFn">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { updateUserPswApi } from '../../api/user'
export default {
  data () {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('密码不能为空,请再次输入密码'))
      } else if (value !== this.resetForm.re_pwd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      // 校验
      resetForm: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      rulesForm: {
        old_pwd: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { min: 3, max: 6, message: '请输入3-6位用户名', trigger: 'blur' }
        ],
        new_pwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 3, max: 6, message: '请输入3-6位密码', trigger: 'blur' }
        ],
        re_pwd: [
          { required: true, message: '请输入确认新密码', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    modifyPwdFn () {
      this.$refs.resetPwdRef.validate(async (valid) => {
        if (valid) {
          const res = await updateUserPswApi(this.resetForm)
          console.log(res, 'reset')
          if (res.data.code === 0) {
            this.$message.success(res.data.message)
            // 清除token并重新登录
            localStorage.removeItem('token')
            // 并回到登录页面  要求客户重新登录
            this.$router.push('/login')
          } else {
            this.$message.error(res.data.message)
          }
        }
      })
    },
    resetFn () {
      this.$refs.resetPwdRef.resetFields()
    }
  }
}
</script>

<style>
.el-form {
  text-align: left;
  width: 500px;
  margin-top: 20px;
}
</style>
